/*
 * Middleware
 * Copyright (C) 2010/11
 * Riccardo Pulvirenti, Giuseppe Ravidà, Andrea Tino
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANDABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses
 */

/*!
 * File: worker_discovery_proxy.cpp
 */

#include <boost/asio.hpp>
#include <exception>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>

#include "worker_discovery_proxy.hpp"

using namespace middleware;

//-----------------------------------------------------------------------------
// Constructors and destructor
/* Private constructor */
WorkerDiscoveryProxy::WorkerDiscoveryProxy() {
	(this->_config).proxy_ipaddr = "127.0.0.1";
	(this->_config).proxy_port = "0";
}
/* Private paranetric constructor */
WorkerDiscoveryProxy::WorkerDiscoveryProxy(WorkerDiscProxyConfig conf) {
	(this->_config).proxy_ipaddr = conf.proxy_ipaddr;
	(this->_config).proxy_port = conf.proxy_port;
}
/* Destructor */
WorkerDiscoveryProxy::~WorkerDiscoveryProxy() {

}
//-----------------------------------------------------------------------------
// Public members
/* Getting worker */
Address WorkerDiscoveryProxy::get_worker(const TaskDescriptor& taskdesc)
		throw(ProxyException) {
	using boost::asio::ip::tcp;
	try {
		// TODO
	} catch(std::exception& e) {
		throw ProxyException(std::string("Error in proxy: ") + e.what());
	}
}
/* Updating worker */
void WorkerDiscoveryProxy::update_worker(const WorkerDescriptor& workerdesc)
		throw(ProxyException) {
	using boost::asio::ip::tcp;
	try {
		tcp::iostream wdesc_stream(this->_config.proxy_ipaddr,
				this->_config.proxy_port); /* Creating TCP stream */
		if (!wdesc_stream) {
			throw ProxyException("Unable to open TCP stream!");
		} else {
			boost::archive::binary_oarchive oa(wdesc_stream);
			oa << workerdesc; /* Sending workflow */
			wdesc_stream.close();
		}
	} catch(std::exception& e) {
		throw ProxyException(std::string("Error in proxy: ") + e.what());
	}
}
